import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'

const service = axios.create({
    baseURL: '/api',
    timeout: 5000000
})

service.interceptors.request.use(config =>   {
    if (store.getters.token) {
        config.headers['authToken'] = getToken()
    }
    return config
}, error => {
    Promise.reject(error)
})

service.interceptors.response.use(response => {
    if (response.data && response.data.code == '401') {
        store.dispatch('logOutFont').then(function(){
            router.push("/login")
        })
    } else {
        return response;
    }
    return response;
}, error => {
    if (error.status === 401) {
        store.dispatch('logOutFont').then(function() {
            router.push("/login")
        })
    }
    Message({
        message: error.message,
        type: 'error',
        duration: 5*1000
    })
    return Promise.reject(error)
})

export default service